package Sort;

import java.util.Arrays;

public class HeapSort {

    public void operation(int[] arr) {
        creatHeap(arr);
        int end = arr.length - 1;
        while (end > 0) {
            swap(arr, 0, end);
            siftDown(arr, 0, end - 1);
            end--;
        }
    }

    public void creatHeap(int[] arr) {
        int len = arr.length;

        for (int i = (len - 1 - 1) / 2; i >= 0; i--) {
            siftDown(arr, i, len - 1);
        }
    }

    public void siftDown(int[] arr, int parent, int end) {
        int child = parent * 2 + 1;
        while (child <= end) {
            if (child + 1 <= end && arr[child] < arr[child + 1]) {
                child++;
            }
            if (arr[child] > arr[parent]) {
                swap(arr, child, parent);
            }
            parent = child;
            child = parent * 2 + 1;
        }
    }

    public void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {2,4,5,6,87,6,5,3,2,3,45,56,7};

        HeapSort heapSort = new HeapSort();
        heapSort.operation(arr);
        System.out.println(Arrays.toString(arr));
    }
}
